package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.mapper.ShopMapperM;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private CacheClient cacheClient;
//    @Autowired
//    private ShopMapperM shopMapperM ;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //根据id查询商铺
    @Override
    public Result queryShopById(Long id) {
        //缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, aLong -> getById(aLong), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //互斥锁解决缓存击穿
//        Shop shop = cacheClient.queryWithMutual(LOCK_SHOP_KEY,CACHE_SHOP_KEY, id, Shop.class, (shopId) -> getById(shopId), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        return getResult2(id);

        //逻辑过期解决缓存击穿
//        Shop shop = cacheClient.queryByLogicExpire(LOCK_SHOP_KEY,CACHE_SHOP_KEY, id, Shop.class, (shopId) -> getById(shopId), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        return getResult3(id);

        return Result.ok(shop);
    }


    @Override
    //开启事务
    @Transactional
    public Result updateId(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("id不能为空");
        }

        //更新数据库
        updateById(shop);
        //删除redis的数据
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return null;
    }





//    //解决缓存穿透
//    private Result getResult1(Long id) {
//
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY+ id);
//
//        // 如果redis查询不为空,StrUtil.isNotBlank(shopJson) 空格，换行，null都为blank
//        if (StrUtil.isNotBlank(shopJson)) {
//            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//            return Result.ok(shop);
//        }
//
//        if (shopJson != null){
//            return Result.fail("店铺不存在");
//        }
//
//        //查询数据库
////        Shop shopById = getById(id);
//        Shop shopById = shopMapperM.getById(id);
//
//
//        //放入redis
//        if (shopById != null ){
//            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//        }
//
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shopById),30L,TimeUnit.MINUTES);
//
//        return Result.ok(shopById);
//    }



    //互斥锁解决缓存击穿
//    private Result getResult2(Long id) {
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//
//        // 如果redis查询不为空,StrUtil.isNotBlank(shopJson) 空格，换行，null都为blank
//        if (StrUtil.isNotBlank(shopJson)) {
//            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//            return Result.ok(shop);
//        }
//
//        if (shopJson != null) {
//            return Result.fail("店铺不存在");
//        }
//
//        //查询数据库
////        Shop shopById = getById(id);
//
//        int i = 0;
//        //获取锁
//        boolean flag = setLock(LOCK_SHOP_KEY + id);
//        Shop shop = null;
//        try {
//            while (!flag) {
//                Thread.sleep(50);
//                i++;
//                if (i >= 10) {
//                    return Result.fail("获取失败，请刷新再试");
//                }
//            }
//
//            shop = shopMapperM.getById(id);
//            //放入redis
//            if (shop == null) {
//                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//                return Result.ok();
//            }
//            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);
//            return Result.ok(shop);
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            unlock(LOCK_SHOP_KEY + id);
//            return Result.ok(shop);
//        }
//    }

    //使用逻辑过期解决缓存击穿
//    private Result getResult3(Long id){
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//
//        // 如果redis查询为空,返回空值
//        if (StrUtil.isBlank(shopJson)) {
//            return Result.ok(null);
//        }
//
//        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
//
//        //如果没有超过时间，则直接返回
//        if (expireTime.isAfter(LocalDateTime.now())){
//            return Result.ok(redisData.getData());
//        }
//
//        //超过超时时间，获取锁
//        boolean flag = setLock(LOCK_SHOP_KEY + id);
//        Shop shop = null;
//
//        //获取成功，查询数据库
////        if (flag){
////            CACHE_REBUILD_EXECUTOR.submit(() ->{
////                try{
////                    //重建缓存
////                    this.saveShop(id,20L);
////                }catch (Exception e){
////                    throw new RuntimeException(e);
////                }finally {
////                    unlock(LOCK_SHOP_KEY + id);
////                }
////            });
////        }
//
//        if (flag){
//            CACHE_REBUILD_EXECUTOR.submit(new Runnable() {
//                @Override
//                public void run() {
//                    ShopServiceImpl.this.saveShop(id,20L);
//                }
//            });
//        }
//
//            unlock(LOCK_SHOP_KEY + id);
//            return Result.ok(shop);
//
//    }
//
//
//    //预热热点商铺
//    public void saveShop(Long id ,Long expireTime){
//        Shop shop = getById(id);
//
//        RedisData redisData = new RedisData();
//        redisData.setData(shop);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
//
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id ,JSONUtil.toJsonStr(redisData) );
//    }
//
//    private boolean setLock(String key){
//        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
//        return BooleanUtil.isTrue(aBoolean);
//    }
//    private void unlock(String key) {
//        stringRedisTemplate.delete(key);
//    }
}
